//
//  LLCycleView.m
//  cyclePrac
//
//  Created by 张Kevin on 17/5/30.
//  Copyright © 2017年 Kevin. All rights reserved.
//

#import "LLCycleView.h"
#import <Masonry/Masonry.h>
#import <SDWebImage/UIImageView+WebCache.h>

@interface LLCollectionCell : UICollectionViewCell

@property (nonatomic, strong) UIImageView *imageView;

@end

@implementation LLCollectionCell

-(instancetype)initWithFrame:(CGRect)frame{
    
    self = [super initWithFrame:frame];
    
    if (self) {
        
        _imageView = [[UIImageView alloc]init];
        
        [self.contentView addSubview:_imageView];
        
        [_imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.contentView);
        }];
        
    }
    return self;
}

@end


@interface LLCycleView () <UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate>

@property (nonatomic, strong) UICollectionView  *collectionView;
@property (nonatomic, strong) UIPageControl *pageControl;



@end

@implementation LLCycleView{
    
    NSInteger _count;
    NSTimer *_timer;
}


-(UIPageControl *)pageControl{
    
    if (_pageControl == nil) {
        _pageControl = [[UIPageControl alloc]init];
        
//        _pageControl.pageIndicatorTintColor =[UIColor grayColor];
        _pageControl.enabled = NO;
        [self addSubview:_pageControl];
        
        [_pageControl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.equalTo(self);
            make.height.mas_equalTo(20);
        }];
    }
    return _pageControl;
}

-(UICollectionView *)collectionView{
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    
    flowLayout.headerReferenceSize = CGSizeZero;
    flowLayout.footerReferenceSize = CGSizeZero;
    
    
    if (_collectionView == nil ) {
        
        _collectionView = [[UICollectionView alloc]initWithFrame:self.frame collectionViewLayout:flowLayout];
        
        [self addSubview:_collectionView];
        
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        
        _collectionView.pagingEnabled = YES;

        
        [_collectionView registerClass:[LLCollectionCell class] forCellWithReuseIdentifier:@"cell"];
        
        
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
         
            make.edges.equalTo(self);
         
        }];
    }
    return _collectionView;
}


#pragma mark --reload方法
-(void)reloadData{
    
    [self.collectionView reloadData];
    
    _count = [self numberOfItems];
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(colorForCurrentPageInCycleView:)]) {
       self.pageControl.currentPageIndicatorTintColor = [self.delegate colorForCurrentPageInCycleView:self];
    }
    
    self.pageControl.numberOfPages = _count;
    
    [self layoutIfNeeded];
    
    self.collectionView.contentOffset = CGPointMake(_count *self.frame.size.width, 0);
//    CGSizeMake(_count *self.frame.size.width, 0/);
    //非常重要
    [self startTimer];
    
}

-(NSInteger )numberOfItems{
    
    NSInteger count = 0;
    
    if (self.dataSource && [self.dataSource respondsToSelector:@selector(numberOfRowsInCycleView:)]) {
        
        count = [self.dataSource numberOfRowsInCycleView:self];
    }
    
    
    return  count;
}




#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return _count *100;
}


- (__kindof  LLCollectionCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSInteger idx = indexPath.row % _count;
    
    LLCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    NSURL *url = nil;
    
    if (self.dataSource && [self.dataSource respondsToSelector:@selector(cycleView:imageURLForItemAtIndex:)]) {
        
        url = [self.dataSource cycleView:self imageURLForItemAtIndex:idx];
    }
    
    if(url != nil) {
        if(self.defaultImage == nil) {
            [cell.imageView sd_setImageWithURL:url];
        } else {
            [cell.imageView sd_setImageWithURL:url placeholderImage:self.defaultImage];
        }
    }
    return cell;
}

#pragma mark - UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    return self.collectionView.frame.size;
}




#pragma mark - UIScrollViewDelegate


- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
    
    [self clearTimer];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    self.pageControl.currentPage = (int) (scrollView.contentOffset.x / self.collectionView.frame.size.width ) % _count;
    [self startTimer];

}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    
    self.pageControl.currentPage = (int) (scrollView.contentOffset.x / self.collectionView.frame.size.width ) % _count;
    
}

#pragma mark - timer

- (void)removeFromSuperview {
    [self clearTimer];
}

- (void)startTimer {
    [self clearTimer];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(doTimer) userInfo:nil repeats:YES];
}

- (void)doTimer {
    CGPoint offset = CGPointMake(self.collectionView.contentOffset.x + self.collectionView.frame.size.width, self.collectionView.contentOffset.y);
    if(offset.x >= self.collectionView.contentSize.width - self.collectionView.frame.size.width) {
        offset.x = 0;
    }
    
    
    [self.collectionView setContentOffset:offset animated:YES];
}



- (void)clearTimer {
    if(_timer != nil) {
        if([_timer isValid]) {
            [_timer invalidate];
        }
        _timer = nil;
    }
}




@end
